from datetime import datetime
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec


class BasePage():

    def __init__(self):
        self.driver=webdriver.Chrome()

    def get_url(self,url):
        self.driver.get(url)

    def find_ele(self,loc,msg):
        try:
            self.wait(loc)
            ele=self.driver.find_element(*loc)
            print('元素%s定位成功' % str(loc))
            return ele
        except Exception as e:
            print('元素%s定位失败' % str(loc))
            self.get_photo(msg)
            return None

    def wait(self,loc,time=20,poll=0.5):
        print('开始等元素%s' % str(loc))
        try:
            start_time = datetime.now()
            WebDriverWait(self.driver, time, poll).until(ec.visibility_of_element_located(loc))
            end_time = datetime.now()
            times = (end_time - start_time).seconds
            print('元素%s等待成功，用时%s秒' % (str(loc), times))
            return True
        except Exception as e:
            print('元素%s等待失败' % str(loc))
            return False

    def get_photo(self,msg):
        path = '../test_results/images/' + msg + '.png'
        self.driver.get_screenshot_as_file(path)

    def input_text(self, locator, msg, text):
        """
        输入操作
        :param locator: 定位方式
        :param msg: 截图名称
        :param text: 输入内容
        :return:
        """
        ele = self.find_ele(locator, msg)
        if ele is not None:
            ele.send_keys(text)
        else:
            print("未找到元素，不能进行输入操作")

    def click_ele(self, locator, msg):
        """
        点击操作
        :param locator:
        :param msg:
        :return:
        """
        ele = self.find_ele(locator, msg)
        if ele is not None:
            ele.click()
        else:
            print("未找到元素，不能进行点击操作")

    def get_element_text(self, locator, msg):
        """
        获取指定元素的文本值
        :param locator:
        :param msg:
        :return:
        """
        ele = self.find_ele(locator, msg)
        text = None
        if ele is not None:
            text = ele.text
        else:
            print("未找到元素，不能获取文本数据")

        return text

    def get_element_attribute(self, locator, msg, attribute):
        """
        获取元素的指定属性值
        :param locator:
        :param msg:
        :param attribute:
        :return:
        """
        ele = self.find_ele(locator, msg)
        value = None
        if ele is not None:
            value = ele.get_attribute(attribute)
        else:
            print("未找到元素，不能获取元素属性")

        return value